<?php

namespace App\Console\Commands;

use App\model\Area;
use App\model\Coustomer;
use App\model\Industry;
use App\model\Source;
use App\Repository\CustomerRepository;
use App\shiyou\Form;
use App\shiyou\Form1;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;

class Shiyou extends Command
{
    protected $project_id=15;
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'shiyou:form {form}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
       $customerRespository= new CustomerRepository();
       switch ($this->argument('form')){
           case  1:
               $form=Form::query();
               break;
           case 2:
               $form=Form1::query();
               break;

       }
       $form->chunkById(100,function($forms)use($customerRespository){
           foreach ($forms as $v){
               $coustomer=Coustomer::whereMobile($v->mobile)
                   ->where('name',$v->name)
                   ->where('project_id',$this->project_id)
                   ->where('created_at',\Illuminate\Support\Carbon::createFromTimestamp($v->datetime)->toDateTimeString())
                   ->first();

               if ($coustomer){

               //    $coustomer->created_at=\Illuminate\Support\Carbon::createFromTimestamp($v->datetime);
              //     $coustomer->save();
                   $this->info($coustomer->customer_id);
               }

               if (!$coustomer){
                   $coustomer=new Coustomer();
                   $coustomer->name=$v->name;
                   $coustomer->mobile=$v->mobile;
                   $coustomer->project_id=$this->project_id;
                   $coustomer->created_at=\Illuminate\Support\Carbon::createFromTimestamp($v->datetime);

                   if ($v->cfmj){
                       $area=Area::firstOrCreate(['name'=>$v->cfmj]);
                       $coustomer->area_id=$area->id;
                   }
                    $scource=Source::firstOrCreate(['name'=>'世友自建站']);
                    $coustomer->source_id=$scource->source_id;
                    if ($v->szhy){
                        $industry=Industry::firstOrCreate(['name'=>$v->szhy,'project_id'=>$this->project_id]);
                        $coustomer->industry_id=$industry->industry_id;
                    }
                     $coustomer->save();
                    $customerRespository->sendXiaoshou($coustomer);
               }
           }

       });
    }
}
